/* eslint-disable no-undef */
/* eslint-disable no-unused-vars */
import React, { useCallback, useState } from "react";
import {
  DndContext,
  DragOverlay,
  useDraggable,
  useDroppable,
} from "@dnd-kit/core";
import { theme, Row, Col, Tooltip } from "antd";
import { useModel } from "umi";
import { ProForm, ProFormText } from "@ant-design/pro-components";
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  useSortable,
  rectSortingStrategy,
} from "@dnd-kit/sortable";
import { CloseOutlined, CopyOutlined } from "@ant-design/icons";
import config from "@/layouts/config";
import { CSS } from "@dnd-kit/utilities";
import FormDom from "@/components/DragContainer/formdom";
import { generateRandomString } from "@/utils/fns";

import _ from "loadsh";

function SortableItem({ control, formConfig, index }) {
  const { name, colProps } = control;
  const {
    initialState: { activeItem, updateTemplate },
    setInitialState,
  } = useModel("@@initialState");

  const {
    token: { controlOutline },
  } = theme.useToken();

  const { attributes, listeners, setNodeRef, transform, transition } =
    useSortable({
      id: name,
      data: {
        index,
        id: name,
        control,
      },
    });

  const ifs = activeItem?.name === control?.name;

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    backgroundColor: ifs ? controlOutline : "transparent",
    borderRadius: 6,
    position: "relative",
  };

  return (
    <Col
      ref={setNodeRef}
      style={style}
      {...attributes}
      {...listeners}
      {...colProps}
      onClick={() => {
        setInitialState((s) => ({
          ...s,
          activeItem: control,
          updateTemplate: parseInt(Math.random() * 12),
        }));
      }}
    >
      {ifs && (
        <div
          className={
            formConfig.layout === "vertical" ? "actionbar" : "actionbars"
          }
        >
          <Tooltip title="复制">
            <CopyOutlined
              style={{ cursor: "pointer" }}
              onClick={() => {
                setInitialState((s) => {
                  let news = [...s.formControls],
                    index;
                  news.map((it, i) => {
                    if (it.name === control.name) {
                      index = i;
                    }
                  });
                  news.splice(index + 1, 0, {
                    ...control,
                    name: generateRandomString(8),
                    label: control.label + "new" + generateRandomString(2),
                  });

                  return {
                    ...s,
                    formControls: news,
                  };
                });
              }}
            ></CopyOutlined>
          </Tooltip>
          <Tooltip title="移除">
            <CloseOutlined
              style={{ cursor: "pointer", color: "red" }}
              onClick={() => {
                setInitialState((s) => {
                  let news = [...s.formControls];
                  news = news.filter((it) => it.name !== control.name);
                  return {
                    ...s,
                    formControls: news,
                  };
                });
              }}
            ></CloseOutlined>
          </Tooltip>
        </div>
      )}
      <FormDom control={control}></FormDom>
    </Col>
  );
}

// 主组件
function DragAndDropFormBuilder({ form }) {
  const {
    initialState: { formControls, formConfig },
  } = useModel("@@initialState");

  const {
    token: { colorTextBase, colorBgContainer },
  } = theme.useToken();

  const { attributes, listeners, setNodeRef, transform, transition } =
    useDroppable({
      id: "canvas_droppable",
      data: {
        parent: null,
        isContainer: true,
      },
    });

  return (
    <div
      ref={setNodeRef}
      {...attributes}
      {...listeners}
      style={{
        width: "100%",
        height: "calc(100vh - 36px)",
        padding: 12,
        background: colorBgContainer,
        transform: CSS.Transform.toString(transform),
        transition,
      }}
    >
      <ProForm style={{width:'100%',height:'100%'}} form={form} submitter={false} layout={formConfig?.layout}>
        {formControls.length === 0 && (
          <div
            className="center"
            style={{
              width: "100%",
              height: "100%",
              color: colorTextBase,
              opacity: 0.5,
            }}
          >
            请使用鼠标从左侧拖动组件放置于此处.
          </div>
        )}

        <Row {...formConfig?.rowProps}>
          {formControls.map((control, index) => {
            return (
              <SortableItem
                key={index}
                index={index}
                control={control}
                formConfig={formConfig}
              />
            );
          })}
        </Row>
      </ProForm>
    </div>
  );
}

export default DragAndDropFormBuilder;
